import type { AxiosRequestConfig } from 'axios';
import { retryEventBus } from './retryEventBus';

// 扩展AxiosRequestConfig接口，添加重试标记
interface ExtendedAxiosRequestConfig extends AxiosRequestConfig {
  _retry?: boolean;
}

// 请求队列项接口
export interface QueuedRequest {
  id: string;
  config: ExtendedAxiosRequestConfig;
  resolve: (value: any) => void;
  reject: (reason?: any) => void;
  timestamp: number;
}

// 请求队列管理器
class RequestQueue {
  private queue: QueuedRequest[] = [];
  private maxRetries = 3; // 最大重试次数
  private retryDelay = 1000; // 重试延迟（毫秒）

  /**
   * 添加请求到队列
   */
  addRequest(config: AxiosRequestConfig): Promise<any> {
    return new Promise((resolve, reject) => {
      const requestId = this.generateRequestId();
      const queuedRequest: QueuedRequest = {
        id: requestId,
        config,
        resolve,
        reject,
        timestamp: Date.now(),
      };

      this.queue.push(queuedRequest);
      console.log('请求已添加到队列:', requestId, config.url);
    });
  }

  /**
   * 重试队列中的所有请求
   */
  async retryAllRequests(axiosInstance: any) {
    if (this.queue.length === 0) {
      console.log('队列为空，无需重试');
      return;
    }

    console.log(`开始重试 ${this.queue.length} 个请求`);

    const requests = [...this.queue];
    this.queue = []; // 清空队列

    const retryPromises = requests.map(async (queuedRequest) => {
      try {
        console.log('重试请求:', queuedRequest.id, queuedRequest.config.url);

        // 清除重试标记，允许正常请求
        delete queuedRequest.config._retry;

        const response = await axiosInstance(queuedRequest.config);
        console.log('请求重试成功:', queuedRequest.id, response);

        // 触发重试成功事件
        retryEventBus.addRetryEvent({
          type: 'request_retry_success',
          requestId: queuedRequest.id,
          url: queuedRequest.config.url || '',
          data: response,
        });

        // 确保返回的数据格式正确
        queuedRequest.resolve(response);
        return { success: true, id: queuedRequest.id };
      } catch (error) {
        console.error('请求重试失败:', queuedRequest.id, error);
        queuedRequest.reject(error);
        return { success: false, id: queuedRequest.id, error };
      }
    });

    // 等待所有重试完成
    const results = await Promise.allSettled(retryPromises);

    const successCount = results.filter(
      (result) => result.status === 'fulfilled' && result.value.success
    ).length;

    console.log(`重试完成: ${successCount}/${requests.length} 个请求成功`);
  }

  /**
   * 清空队列
   */
  clearQueue() {
    this.queue.forEach((queuedRequest) => {
      queuedRequest.reject(new Error('请求被取消'));
    });
    this.queue = [];
    console.log('请求队列已清空');
  }

  /**
   * 获取队列长度
   */
  getQueueLength(): number {
    return this.queue.length;
  }

  /**
   * 生成请求ID
   */
  private generateRequestId(): string {
    return `req_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
  }

  /**
   * 清理过期请求（超过5分钟的请求）
   */
  cleanExpiredRequests() {
    const now = Date.now();
    const expiredTime = 5 * 60 * 1000; // 5分钟

    this.queue = this.queue.filter((queuedRequest) => {
      const isExpired = now - queuedRequest.timestamp > expiredTime;
      if (isExpired) {
        queuedRequest.reject(new Error('请求已过期'));
        console.log('清理过期请求:', queuedRequest.id);
      }
      return !isExpired;
    });
  }
}

// 创建全局请求队列实例
export const requestQueue = new RequestQueue();

// 定期清理过期请求
setInterval(() => {
  requestQueue.cleanExpiredRequests();
}, 60000); // 每分钟清理一次
